<template>
  <div>
    <div
        class="topSearch"
        style="margin-bottom: 10px; display: flex; justify-content: space-between"
    >
      <div>
        <!--         <span>仓库： <el-select size="small"-->
        <!--                              style="width: 250px" v-model="params.areaId" clearable>-->
        <!--                <el-option v-for="item in warehouseList" :label="item.areaName" :value="item.area"-->
        <!--                           :key="item.area"></el-option>-->
        <!--              </el-select></span>-->

        <span style="margin-left: 15px"
        >门店名称：<el-input
            size="small"
            style="width: 250px"
            v-model="params.storeName"
            clearable
        ></el-input
        ></span>

        <span style="margin-left: 15px">所属仓库：</span>
        <el-select
            clearable
            v-model="params.areaId"
            size="small"
            style="width: 200px"
            placeholder="请选择"
        >
          <el-option
              v-for="item in warehouseList"
              :key="item.area"
              :label="item.areaName"
              :value="item.area"
          />
        </el-select>
        <span style="text-align: center; margin-left: 20px"
        >品牌方：
          <el-select
              v-model="params.systemType"
              placeholder="请按品牌方搜索"
              size="small"
              style="width: 200px"
          >
            <el-option
                :value="item.id"
                :label="item.systemName"
                :key="item.id"
                v-for="item in systemList"
            ></el-option>
          </el-select>
        </span>
        <span style="margin-left: 15px">
          <el-button size="small" type="primary" @click="_search"
          >搜 索</el-button
          >
          <el-button size="small" type="info" @click="_reset">重 置</el-button>
        </span>
      </div>
      <div>
        <el-button size="small" type="primary" @click="_add"
        >新 增
        </el-button
        >
        <el-button type="primary" size="small" @click="downloadDetailReport"
        ><i class="el-icon-download"></i>老店升级表下载
        </el-button>
      </div>
    </div>
    <div class="centerTable">
      <el-table
          :data="finaceDetailData"
          height="calc(100vh - 250px)"
          :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
          :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
        }"
      >
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="storeName" label="门店名称"></el-table-column>
        <el-table-column prop="systemName" label="所属品牌"></el-table-column>
        <el-table-column prop="areaName" label="所属仓库"></el-table-column>
        <el-table-column
            v-for="col in editableColumns"
            :key="col.prop"
            :prop="col.prop"
            :label="col.label"
        >
          <template v-slot:default="scope">
            <el-input
                v-if="scope.row.isEditing[col.prop]"
                v-model="scope.row[col.prop]"
                @blur="blurEvent(scope.row, scope.$index, col.prop)"
                v-focus
            ></el-input>
            <!--            <div v-else-if="col.prop === 'payTime'">-->
            <!--              {{ scope.row.payTime }}-->
            <!--            </div>-->
            <div v-else-if="col.prop === 'payProofList'">
              <div style="display: flex">
                <el-image
                    v-for="(item, index) in scope.row.payProofList"
                    :key="index"
                    :src="host + item"
                    :preview-src-list="
                    scope.row.payProofList.map((img) => host + img)
                  "
                    class="img-item"
                    fit="cover"
                >
                </el-image>
              </div>
            </div>
            <div v-else-if="col.prop === 'customerRefundProofList'">
              <div style="display: flex">
                <el-image
                    v-for="(item, index) in scope.row.customerRefundProofList"
                    :key="index"
                    :src="host + item"
                    :preview-src-list="
                    scope.row.customerRefundProofList.map((img) => host + img)
                  "
                    class="img-item"
                    fit="cover"
                >
                </el-image>
              </div>
            </div>
            <div v-else-if="col.prop === 'financialPaymentProofList'">
              <div style="display: flex">
                <el-image
                    v-for="(item, index) in scope.row.financialPaymentProofList"
                    :key="index"
                    :src="host + item"
                    :preview-src-list="
                    scope.row.financialPaymentProofList.map((img) => host + img)
                  "
                    class="img-item"
                    fit="cover"
                >
                </el-image>
              </div>
            </div>
            <div v-else-if="col.prop === 'orderProofList'">
              <div style="display: flex">
                <el-image
                    v-for="(item, index) in scope.row.orderProofList"
                    :key="index"
                    :src="host + item"
                    :preview-src-list="
                    scope.row.orderProofList.map((img) => host + img)
                  "
                    class="img-item"
                    fit="cover"
                >
                </el-image>
              </div>
            </div>
            <p v-else @click="cellClick(scope.row, col.prop)">
              {{ scope.row[col.prop] }}
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="a" label="操作">
          <template v-slot:default="scope">
            <el-link
                style="
                color: #66b1ff;
                text-decoration: underline;
                margin-right: 10px;
              "
                @click="_edit(scope.row)"
            >编 辑
            </el-link>
            <el-link
                v-if="userName=='曹紫芳'"
                style="
                color: #ce0e0f;
                text-decoration: underline;
                margin-right: 10px;
              "
                @click="_delete(scope.row)"
            >删 除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          style="padding: 20px 0"
          align="right"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[20, 30, 40, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      >
      </el-pagination>
    </div>
    <div>
      <el-dialog
          :visible.sync="dialogAdd"
          :title="title"
          top="10px"
          width="40%"
      >
        <div style="height: calc(100vh - 250px); overflow-y: auto">
          <el-row>
            <el-col :span="12">
              <span style="width: 50px">店名：</span>
              <el-input
                  size="small"
                  style="width: 280px"
                  v-model="data.storeName"
              ></el-input>
            </el-col>
            <el-col :span="12">
              <span style="width: 50px">品牌：</span>
              <el-select
                  size="small"
                  style="width: 280px"
                  v-model="data.systemType"
              >
                <el-option
                    :value="item.id"
                    :label="item.systemName"
                    :key="item.id"
                    v-for="item in systemList"
                ></el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <span style="width: 50px">仓库：</span>
              <el-select
                  clearable
                  size="small"
                  v-model="data.areaId"
                  :disabled="disabled"
                  style="width: 280px"
                  placeholder="请选择"
              >
                <el-option
                    v-for="item in warehouseList"
                    :key="item.area"
                    :label="item.areaName"
                    :value="item.area"
                />
              </el-select>
            </el-col
            >
          </el-row>
          <!--        -->
          <el-row>
            <el-col :span="12">
              <span>报价单运费：</span>
              <el-input-number
                  v-model="data.bjdFee"
                  :min="0"
                  size="small"
                  style="width: 200px"
                  @change="changeNum('bjdFee', $event)"
              ></el-input-number>
            </el-col>
            <el-col :span="12">
              <span>发货费用：</span>
              <el-input-number
                  v-model="data.fhdFee"
                  :min="0"
                  size="small"
                  style="width: 200px"
                  @change="changeNum('fhdFee', $event)"
              ></el-input-number>
            </el-col>
          </el-row>
          <!--        -->
          <el-row>
            <el-col :span="12">
              <span>报价单安装费：</span>
              <el-input-number
                  v-model="data.bjdInstallFee"
                  :min="0"
                  size="small"
                  style="width: 200px"
                  @change="changeNum('bjdInstallFee', $event)"
              ></el-input-number>
            </el-col>
            <el-col :span="12">
              <span>安装费用:</span>
              <el-input-number
                  v-model="data.installFee"
                  :min="0"
                  size="small"
                  style="width: 200px"
                  @change="changeNum('installFee', $event)"
              ></el-input-number>
            </el-col>
          </el-row>
          <!--        -->
          <el-row>
            <el-col :span="12">
              <span>二次上门:</span>
              <el-input-number
                  v-model="data.secondVisit"
                  :min="0"
                  size="small"
                  style="width: 200px"
                  @change="changeNum('secondVisit', $event)"
              ></el-input-number>
            </el-col>
            <el-col :span="12">
              <span>三次上门:</span>
              <el-input-number
                  v-model="data.thirdVisit"
                  :min="0"
                  size="small"
                  style="width: 200px"
                  @change="changeNum('thirdVisit', $event)"
              ></el-input-number>
            </el-col>
          </el-row>
          <!--        -->
          <el-row>
            <el-col :span="12">
              <span>客户退费:</span>
              <el-input-number
                  v-model="data.customerRefund"
                  :min="0"
                  size="small"
                  style="width: 200px"
                  @change="changeNum('customerRefund', $event)"
              ></el-input-number>
            </el-col>
            <el-col :span="12">
              <span>欠数补发:</span>
              <el-input-number
                  v-model="data.qpReissue"
                  :min="0"
                  size="small"
                  style="width: 200px"
                  @change="changeNum('qpReissue', $event)"
              ></el-input-number>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <span>运费:</span>
              <el-input-number
                  v-model="data.freight"
                  :min="0"
                  size="small"
                  style="width: 200px"
                  @change="changeNum('freight', $event)"
              ></el-input-number>
            </el-col>
            <el-col :span="12">
              <span style="width: 70px;">物流单号：</span>
              <el-input
                  size="small"
                  style="width: 250px"
                  v-model="data.courierNumber"
              ></el-input>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <span style="width: 70px">实付金额：</span>
              <el-input
                  size="small"
                  style="width: 250px"
                  v-model="data.payMoney"
              ></el-input>
            </el-col>
            <el-col :span="12">
              <span style="width: 50px">卡号：</span>
              <el-input
                  size="small"
                  style="width: 250px"
                  v-model="data.card"
              ></el-input>
            </el-col>
          </el-row>
          <!--          <el-row>-->
          <!--            <el-col :span="12">-->
          <!--              <span style="width: 70px">付款日期：</span>-->
          <!--              <el-date-picker-->
          <!--                  v-model="data.payTime"-->
          <!--                  type="date"-->
          <!--                  size="small"-->
          <!--                  style="width: 260px"-->
          <!--                  value-format="yyyy-MM-dd"-->
          <!--                  placeholder="选择日期">-->
          <!--              </el-date-picker>-->
          <!--            </el-col>-->
          <!--          </el-row>-->
          <div style="margin-top: 15px">
            <el-row style="display: flex; align-items: center">
              <el-col style="display: flex; align-items: center">
                <span>下单凭证：</span>
                <el-upload
                    multiple
                    class="uploader-wrap"
                    :headers="headers"
                    :action="`${$apiHost}/common/fileImgUrl`"
                    :on-success="paySuc"
                    :show-file-list="false"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">
                    只能上传jpg/png文件，且不超过500kb
                  </div>
                  <template #tip>
                    <div class="img-wrap" style="display: flex">
                      <div
                          v-for="(item, index) in orderProofList"
                          :key="index"
                      >
                        <el-image
                            :key="index"
                            :src="host + item"
                            :preview-src-list="
                            orderProofList.map((img) => host + img)
                          "
                            class="img-item"
                            fit="cover"
                        >
                        </el-image>
                        <div @click="deletePic(index)">
                          <el-icon name="delete"></el-icon>
                        </div>
                      </div>
                    </div>
                  </template>
                </el-upload>
              </el-col>
              <el-col>
                <span>客户付款截图：</span>
                <div>
                  <span style="color: gray; font-size: 12px"
                  >(粘贴复制即可上传图片)</span
                  >
                  <div class="div" style="display: flex; align-items: center">
                    <div
                        v-for="(v, i) in payProofList"
                        style="
                        display: flex;
                        align-items: center;
                        margin-right: 10px;
                      "
                        :key="i"
                    >
                      <el-image
                          v-if="v"
                          :key="i"
                          style="width: 50px; height: 50px"
                          ref="preview"
                          :src="host + v"
                          :preview-src-list="[host + v]"
                      >
                      </el-image>
                      <!-- v-show="!editDetails" -->
                      <div @click="deleteImgVouchers(i)">
                        <el-icon name="delete"></el-icon>
                      </div>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col style="display: flex; align-items: center">
                <span>财务付款凭证：</span>
                <el-upload
                    multiple
                    class="uploader-wrap"
                    :headers="headers"
                    :action="`${$apiHost}/common/fileImgUrl`"
                    :on-success="paySuc1"
                    :show-file-list="false"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">
                    只能上传jpg/png文件，且不超过500kb
                  </div>
                  <template #tip>
                    <div class="img-wrap" style="display: flex">
                      <div
                          v-for="(item, index) in financialPaymentProofList"
                          :key="index"
                      >
                        <el-image
                            :key="index"
                            :src="host + item"
                            :preview-src-list="
                            financialPaymentProofList.map((img) => host + img)
                          "
                            class="img-item"
                            fit="cover"
                        >
                        </el-image>
                        <div @click="deletePic(index)">
                          <el-icon name="delete"></el-icon>
                        </div>
                      </div>
                    </div>
                  </template>
                </el-upload>
              </el-col>
              <el-col style="display: flex; align-items: center">
                <span>客户退款凭证：</span>
                <el-upload
                    multiple
                    class="uploader-wrap"
                    :headers="headers"
                    :action="`${$apiHost}/common/fileImgUrl`"
                    :on-success="paySuc2"
                    :show-file-list="false"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">
                    只能上传jpg/png文件，且不超过500kb
                  </div>
                  <template #tip>
                    <div class="img-wrap" style="display: flex">
                      <div
                          v-for="(item, index) in customerRefundProofList"
                          :key="index"
                      >
                        <el-image
                            :key="index"
                            :src="host + item"
                            :preview-src-list="
                            customerRefundProofList.map((img) => host + img)
                          "
                            class="img-item"
                            fit="cover"
                        >
                        </el-image>
                        <div @click="deletePic(index)">
                          <el-icon name="delete"></el-icon>
                        </div>
                      </div>
                    </div>
                  </template>
                </el-upload>
              </el-col>
            </el-row>
          </div>
        </div>
        <span slot="footer">
          <el-button @click="dialogAdd = false">取 消</el-button>
          <el-button type="primary" @click="_submit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {localStorageAsync, downloadReportWithImage} from '@/utils/public'
import axios from 'axios'
import ExcelJS from "exceljs";
import quinn from "../../utils/quinn";
// import { Message } from 'element-ui'
export default {
  name: 'olderStoreUpgrade',
  data() {
    return {
      dialogAdd: false,
      disabled: false,
      title: '',
      date: '',
      areaId: '',
      num: 0,
      currentPage: 1,
      total: 0,
      host: this.$imgHost,
      warehouseList: [],
      financialPaymentProofList: [],
      customerRefundProofList: [],
      editableColumns: [
        {prop: 'bjdFee', label: '报价单运费'},
        {prop: 'fhdFee', label: '发货费用'},
        {prop: 'bjdInstallFee', label: '报价单安装费'},
        {prop: 'installFee', label: '安装费用'},
        {prop: 'secondVisit', label: '二次上门'},
        {prop: 'thirdVisit', label: '三次上门'},
        {prop: 'orderProofList', label: '下单凭证'},
        {prop: 'payProofList', label: '客户付款凭证'},
        {prop: 'customerRefundProofList', label: '客户退款凭证'},
        {prop: 'financialPaymentProofList', label: '财务付款凭证'},
        // {prop: 'payTime', label: '付款时间'},
        {prop: 'customerRefund', label: '客户退款'},
        {prop: 'qpReissue', label: '欠数补发'},
        {prop: 'freight', label: '运费'},
        {prop: 'courierNumber', label: '物流单号'},
        {prop: 'payMoney', label: '实付金额'},
        {prop: 'card', label: '卡号'},
      ],
      userName: '',
      data: {
        areaId: '', // 仓库ID
        // areaName: '',
        systemType: '', // 品牌方类型
        storeName: '',
        bjdFee: 0,
        fhdFee: 0,
        bjdInstallFee: 0,
        installFee: 0,
        secondVisit: 0,
        thirdVisit: 0,
        customerRefund: 0,
        qpReissue: 0,
        freight: 0,
        courierNumber: 0,
      },
      editId: '',
      params: {
        storeName: '',
        areaId: '',
        systemType: '',
        pageNumber: 1,
        pageSize: 20,
      },
      orderImg: [],
      systemList: [],
      orderProofList: [],
      productData: [],
      payProofList: [],
      finaceDetailData: [],
    }
  },
  computed: {
    headers() {
      const token = this.$quinn.getStorage('token')
      return {
        token,
      }
    },
  },
  directives: {
    focus: {
      inserted: function (el) {
        el.querySelector('input').focus()
      },
    },
  },
  created() {
    this.areaList()
    this.getData()
    this.getSystemType()
    document.addEventListener('paste', this.handlePaste)
    const {userName = []} = quinn.getStorage("userData") || {};
    this.userName = userName
  },
  methods: {
    /**
     * 方法说明 处理粘贴
     * author: iceyhu
     * description:
     * @param
     * @return
     * @createTime: DATE_TIME
     */
    handlePaste(event) {
      if (!this.dialogAdd) return
      const clipboardData = event.clipboardData || window.clipboardData
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i]
          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile()
            if (file) {
              this.uploadImage(file) // 处理文件上传逻辑
            }
          } else {
            this.$message.error('请拷贝图片!')
            break
          }
        }
      }
    },
    deleteImgVouchers(i) {
      this.payProofList.splice(i, 1)
    },
    uploadImage(imageFile) {
      console.log('imageFile', imageFile)
      const formData = new FormData()
      formData.append('file', imageFile)
      axios
          .post(`${this.$apiHost}/common/fileImgUrl`, formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              token: window.$quinn.getStorage('token'),
            },
          })
          .then((response) => {
            this.payProofList.push(response.data.result[0])
          })
          .catch((error) => {
          })
    },
    getSystemType() {
      this.$api.orderGetSystemTypeVo().then((res) => {
        this.systemList = res
      })
    },
    async _submit() {
      try {
        const apiMap = {
          新增: this.$api.financeAddOldStoreDetailFee,
          编辑: this.$api.financeUpdateOldStoreDetailFee,
        }
        const apiFunc = apiMap[this.title]
        if (!apiFunc) return
        const subData = {
          ...this.data,
          payProofList: this.payProofList,
          customerRefundProofList: this.customerRefundProofList,
          financialPaymentProofList: this.financialPaymentProofList,
          orderProofList: this.orderProofList,
        }
        if (!subData.afterTime) delete subData.afterTime
        if (this.title == '编辑') subData.id = this.editId
        const resDate = await apiFunc(subData)
        if (resDate == 1) {
          this.$message.success(`${this.title}成功！`)
          this.dialogAdd = false
          await this.getData()
        }
      } catch (err) {
        console.error('接口请求出错：', err)
        this.$message.error('操作失败，请稍后重试')
      }
    },
    blurEvent(row, index, column) {
      row.isEditing[column] = false
      const payload = {
        id: row.id,
        [column]: row[column],
      }
      this.$api.financeUpdateOldStoreDetailFee(payload).then((res) => {
        if (res == 1) {
          this.$message.success('修改成功！')
          this.getData()
        }
      })
    },
    cellClick(row, column) {
      //input编辑
      Object.keys(row.isEditing).forEach((key) => {
        row.isEditing[key] = false
      })
      // 取消
      row.isEditing[column] = true
    },
    handleSizeChange(val) {
      this.params.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.params.pageNumber = val
      this.getData()
    },
    _search() {
      this.params.pageNumber = 1
      this.getData()
    },
    _reset() {
      this.params = this.$options.data().params
      this.getData()
    },
    /**
     * 方法说明
     * author: iceyhu
     * description:
     * @param{String} dataPurpose 获取数据用途 [default||download]
     * @return
     * @createTime: DATE_TIME
     */
    async getData(dataPurpose = 'default') {
      // console.log('dataPurpose', dataPurpose)
      if (dataPurpose == 'default') {
        const result = await localStorageAsync.removeItem('download')
        if (result == 'success') {
          this.$api.financeGetOldStoreDetailList(this.params).then((res) => {
            res.data.map((el) => {
              el.isEditing = {}
              this.editableColumns.forEach((col) => {
                el.isEditing[col.prop] = false
              })
            })
            this.finaceDetailData = res.data
            this.total = res.total
          })
        }
      }
    },
    getImageBase64(url) {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.crossOrigin = 'anonymous';
        img.onload = function () {
          const canvas = document.createElement('canvas');
          canvas.width = img.width;
          canvas.height = img.height;
          const ctx = canvas.getContext('2d');
          ctx.drawImage(img, 0, 0);
          resolve(canvas.toDataURL('image/png'));
        };
        img.onerror = reject;
        img.src = url;
      });
    },
    async downloadDetailReport() {
      const res = await this.$api.financeGetOldStoreDetailList({
        pageSize: 10000,
        pageNum: 1,
      }).then()
      this.$message('正在导出，请稍等~');
      const workbook = new ExcelJS.Workbook();
      const worksheet = workbook.addWorksheet('Sheet1');
      const headers = [
        '门店名称',
        // '所属品牌',
        '所属仓库',
        '报价单运费',
        '发货费用',
        '报价单安装费',
        '安装费用',
        '二次上门',
        '三次上门',
        '下单凭证',
        '付款凭证',
        '客户退款',
        '欠数补发',
        '运费',
        '物流单号',
        '实付金额',
        '卡号',
      ];
      // 添加标题行
      const titleRow = worksheet.addRow(headers);
      // 设置列宽
      worksheet.columns = headers.map((item, index) => {
        if (index == 8) {
          // 交易截图
          return {
            width: 50,
            alignment: {vertical: 'middle', horizontal: 'center'} // 所有列居中
          }
        } else {
          return {
            width: 20,
            alignment: {vertical: 'middle', horizontal: 'center'} // 所有列居中
          }
        }
      });

      // 设置首行样式：紫色背景、白色加粗字体、居中
      titleRow.eachCell(cell => {
        cell.fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: {argb: '800080'}
        };
        cell.font = {
          bold: true,
          color: {argb: 'FFFFFF'}
        };
        cell.alignment = {vertical: 'middle', horizontal: 'center'};
      });

      for (const el of res.data) {
        const row = worksheet.addRow([
          el.storeName,
          el.areaName,
          el.bjdFee,
          el.fhdFee,
          el.bjdInstallFee,
          el.installFee,
          el.secondVisit,
          el.thirdVisit,
          '', // 图片位置
          '',
          el.customerRefund,
          el.qpReissue,
          el.freight,
          el.courierNumber,
          el.payMoney,
          el.card,
        ]);

        const images = Array.isArray(el.orderProofList)
            ? el.orderProofList
            : el.orderProofList ? [el.orderProofList] : [];
        const images1 = Array.isArray(el.payProofList)
            ? el.payProofList
            : el.payProofList ? [el.payProofList] : [];

        const imageHeight = 80;
        const imageWidth = 100;
        const gap = 10;

        let totalWidth = images.length * (imageWidth + gap);

        if (images.length > 0) {
          worksheet.getRow(row.number).height = imageHeight + 10;

          for (let i = 0; i < images.length; i++) {
            try {
              const base64 = await this.getImageBase64('https://' + images[i]);

              const imageId = workbook.addImage({
                base64: base64,
                extension: 'png'
              });

              worksheet.addImage(imageId, {
                tl: {
                  col: 8 + (i * 0.99), // 控制偏移列位置（让图片横向排列在一格里）
                  row: row.number - 1
                },
                ext: {width: imageWidth, height: imageHeight}
              });

            } catch (err) {
              console.warn('图片插入失败:', 'https://' + images[i], err);
            }
          }
        }
        if (images1.length > 0) {
          worksheet.getRow(row.number).height = imageHeight + 10;

          for (let i = 0; i < images1.length; i++) {
            try {
              const base64 = await this.getImageBase64('https://' + images1[i]);

              const imageId = workbook.addImage({
                base64: base64,
                extension: 'png'
              });

              worksheet.addImage(imageId, {
                tl: {
                  col: 9 + (i * 0.99), // 控制偏移列位置（让图片横向排列在一格里）
                  row: row.number - 1
                },
                ext: {width: imageWidth, height: imageHeight}
              });

            } catch (err) {
              console.warn('图片插入失败:', 'https://' + images1[i], err);
            }
          }
        }
      }
      const buffer = await workbook.xlsx.writeBuffer();
      saveAs(new Blob([buffer]), `老店升级空间扩展.xlsx`);
      this.downIsLoad = false
    },
    // getData() {
    //   const params = this.params
    //   this.$api.financeGetDetailList(params).then((res) => {
    //     res.data.map((el) => {
    //       el.isEditing = {}
    //       this.editableColumns.forEach((col) => {
    //         el.isEditing[col.prop] = false
    //       })
    //     })
    //     this.finaceDetailData = res.data
    //     this.total = res.total
    //   })
    // },
    _add() {
      this.dialogAdd = true
      this.title = '新增'
      this.data = this.$options.data().data
      this.payProofList = []
      this.orderProofList = []
    },
    areaList() {
      this.$api.areaLedgerAreaList().then((res) => {
        this.warehouseList = res
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    paySuc(res) {
      if (res.code == 200 && res.result) {
        this.orderProofList.push(res.result[0])
      }
    },
    paySuc1(res) {
      if (res.code == 200 && res.result) {
        this.financialPaymentProofList.push(res.result[0])
      }
    },
    paySuc2(res) {
      if (res.code == 200 && res.result) {
        this.customerRefundProofList.push(res.result[0])
      }
    },
    deletePic(i) {
      this.orderProofList.splice(i, 1)
    },
    changeNum(field, val) {
      if (!val) {
        this.$set(this.data, field, 0)
      }
    },
    _delete(e) {
      const data = {
        id: e.id,
      }
      this.$confirm('确认删除？')
          .then((_) => {
            this.$api.financeDeleteOldStoreDetailFee(data).then((res) => {
              if (res == 1) {
                this.$message.success('删除成功！')
                this.getData()
              }
            })
          })
          .catch((_) => {
            return
          })
    },
    _edit(a) {
      this.dialogAdd = true
      this.editId = a.id
      this.title = '编辑'
      Object.keys(this.data).forEach((key) => {
        if (key in a) {
          this.$set(this.data, key, a[key])
        }
      })
      this.payProofList = a.payProofList || []
      this.orderProofList = a.orderProofList || [] // 回显凭证
      this.customerRefundProofList = a.customerRefundProofList || [] // 回显凭证
      this.financialPaymentProofList = a.financialPaymentProofList || [] // 回显凭证
    },
  }
  ,
}
</script>

<style scoped lang="less">
.el-row {
  margin-bottom: 20px;

  span {
    display: inline-block;
    width: 90px;
  }
}
</style>
